﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using InstrumentCheck.Module;
using InstrumentCheck.SQLHelper;

namespace InstrumentCheck.DAL
{
    public class DraftBox_dal
    {
        public DraftBox_dal()
        { }

        public List<ApplyForm> GetDraftDetail(string strUserNO)
        {
            string sql = "select correctID,Number,Create_date,dbo.f_GetEmpNameByNo(Applicant) Applicanter,Applicant,Fas_NO,";
            sql += "dbo.f_GetItemName(Fas_NO,Fas_Type) ChiName,dbo.f_GetItemSpec(Fas_NO,Fas_Type) Spec,";
            sql += "dbo.f_GetItemModelNO(Fas_NO,Fas_Type) ModelNO  from Correct WHERE FormStatus = 0 and Creater=@Creater";
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter();
            SqlParameter[] para = new SqlParameter[1];
            para[0] = SQLHelper.SQLHelper.CreateParameter("Creater", SqlDbType.VarChar, strUserNO, ParameterDirection.Input);
            SQLHelper.SQLHelper.Fill(da, ds, sql, CommandType.Text, para);

            List<ApplyForm> list = new List<ApplyForm>();
            if (ds.Tables[0].Rows.Count > 0)
                list = ChangeTableToForm(ds.Tables[0]);
            
            return list;
        }

        public List<ApplyForm> ChangeTableToForm(DataTable dt)
        {
            List<ApplyForm> list = new List<ApplyForm>();
            foreach (DataRow row in dt.Rows)
            {
                ApplyForm form = new ApplyForm();
                User Applicant = new User();
                Applicant.EmpNO = row["Applicant"].ToString();
                Applicant.EmpChineseName = row["Applicanter"].ToString();
                form.Applicant = Applicant;

                Item item = new Item();
                item.AssetNO = row["Fas_NO"].ToString();
                item.ChiName = row["ChiName"].ToString();
                item.Spec = row["Spec"].ToString();
                item.ModelNO = row["ModelNO"].ToString();
                form.Item = item;

                form.FormID = int.Parse(row["CorrectID"].ToString());
                if(row["Number"].ToString() != "")
                    form.FormNO = int.Parse(row["Number"].ToString());
                form.ApplyDate = Convert.ToDateTime(row["Create_date"].ToString());
                list.Add(form);
            }

            return list;
        }
    }
}
